package info.batcloud.fanli.api.security.handler;

import com.alibaba.fastjson.JSON;
import info.batcloud.fanli.api.constants.Constants;
import info.batcloud.fanli.api.domain.LoginResult;
import info.batcloud.fanli.core.domain.BusinessResponse;
import info.batcloud.fanli.core.enums.UserLogType;
import info.batcloud.fanli.core.helper.HttpServletRequestHelper;
import info.batcloud.fanli.core.helper.SecurityHelper;
import info.batcloud.fanli.core.service.UrlMappingService;
import info.batcloud.fanli.core.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Inject
    private UserService userService;

    @Inject
    private UrlMappingService urlMappingService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        String state = request.getParameter("state");
        /**
         * 如果有state参数，则说明需要另外处理。
         * */
        if ("invitation".equals(state)) {
            response.sendRedirect(urlMappingService.getWeixinInvitationJumpUrl());
            return;
        }
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        LoginResult loginResult = new LoginResult();
        String weixinBindOpenId = request.getParameter("weixinBindOpenId");
        if (weixinBindOpenId != null) {
            String sessionWeixinBindOpenid = getSessionWeixinBindOpenId(request);
            if (sessionWeixinBindOpenid != null && weixinBindOpenId.equals(sessionWeixinBindOpenid)) {
                this.userService.bindWeixinOpenId(SecurityHelper.loginUserId(), sessionWeixinBindOpenid);
            }
            request.getSession().removeAttribute(Constants.WEIXIN_BIND_OPEN_ID);
        }
        UserService.ProfileIntegrity profileIntegrity = userService.checkUserProfileIntegrity(SecurityHelper.loginUserId());
        loginResult.setPhoneBound(profileIntegrity.isPhone());
        loginResult.setRegionBound(profileIntegrity.isRegion());
        loginResult.setSuperUserBind(profileIntegrity.isSuperUser());
        Object openId = request.getSession().getAttribute(Constants.WEIXIN_BIND_OPEN_ID);
        loginResult.setWeixinBindOpenId(openId == null ? null : openId.toString());
        UserService.LoginTraceInfo loginTraceInfo = new UserService.LoginTraceInfo();
        loginTraceInfo.setIp(HttpServletRequestHelper.getRequestIp(request));
        loginTraceInfo.setType(UserLogType.ACTIVE);
        userService.trace(SecurityHelper.loginUserId(), loginTraceInfo);
        loginResult.setSuccess(true);
        loginResult.setWeixinBound(profileIntegrity.isWeixin());
        loginResult.setUserId(SecurityHelper.loginUserId());
        response.getWriter().write(JSON.toJSONString(BusinessResponse.ok(loginResult)));
        response.getWriter().flush();
    }

    private String getSessionWeixinBindOpenId(HttpServletRequest request) {
        Object openId = request.getSession().getAttribute(Constants.WEIXIN_BIND_OPEN_ID);
        return openId == null ? null : openId.toString();
    }
}
